package com.luoqiz.project.screenBroadcard.server;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.List;

import javax.imageio.ImageIO;

import com.luoqiz.project.screenBroadcard.ScreenOper;

public class ImageSenderThread extends Thread {

	private boolean flag = false;

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	@Override
	public void run() {
		System.out.println("发送端发送广播");
		ScreenOper sp = new ScreenOper();
//		String filepath="d:/dome/"+System.currentTimeMillis()+".jpg";
//		sp.saveScreen(filepath);
		try {
			DatagramSocket sender = new DatagramSocket(15000);
			byte[] buf = new byte[1024 * 61];
			DatagramPacket pack = new DatagramPacket(buf, buf.length);
			SocketAddress address = new InetSocketAddress(Constant.CLIENT_ADDRESS, Constant.CLIENT_PORT);
			pack.setSocketAddress(address);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while (flag) {
				BufferedImage bufferedImage = sp.getScreen();
				baos.reset();
				ImageIO.write(bufferedImage, "jpg", baos);
//				System.out.println(baos.toByteArray().length);
				List<byte[]> l = sp.getListPackage(baos.toByteArray());
				for(byte[] b:l) {
					pack.setData(b);
					sender.send(pack);
				}
			}
			baos.close();
			sender.close();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
